package com.base.cn.platform.os.service.agent.income;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.agent.income.AgentIncomeDao;
import com.base.cn.platform.os.entity.agent.income.AgentIncome;
import com.base.cn.platform.os.entity.agent.income.AgentIncomeInfo;
import com.base.cn.platform.os.entity.agent.user.AgentUser;
import com.base.cn.platform.os.service.agent.user.AgentUserBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 推广员总收益Biz
 *
 * @author LIZHIPENG
 * @since 2018/5/7
 */
@Service
public class AgentIncomeBiz extends BaseBiz<AgentIncome, AgentIncomeDao>{

    @Autowired
    private AgentUserBiz agentUserBiz;

    /**
     * 根据推广员ID查询推广员总收益
     * @param agentUserId 推广员ID
     * @param agentUserData 是否设置推广员数据
     * @return AgentIncome
     */
    public AgentIncome findAgentIncomeById(BigDecimal agentUserId, boolean agentUserData){
        AgentIncome agentIncome = new AgentIncome();
        agentIncome.setAgentUserId(agentUserId);
        agentIncome.setCount(1);
        List<AgentIncome> agentIncomeList = queryAgentIncomeList(agentIncome, agentUserData);
        if(ObjectUtils.isNotEmpty(agentIncomeList)){
            return agentIncomeList.get(0);
        }
        return null;
    }

    /**
     * 查询推广员总收益列表（分页）
     * @param page
     * @param agentIncome
     * @param agentUserData
     * @return
     */
    public PageInfo<AgentIncome> queryAgentIncomeListPage(Pagination page, AgentIncome agentIncome, boolean agentUserData){
        String whereSql = getWhereSql(agentIncome);
        PageInfo<AgentIncome> agentIncomePageInfo = this.findPage(whereSql, page, null);
        agentIncomePageInfo.setList(this.setExtendData(agentIncomePageInfo.getList(), agentUserData));
        return agentIncomePageInfo;
    }

    /**
     * 查询推广员总收益列表（不分页）
     * @param agentIncome
     * @return
     */
    public List<AgentIncome> queryAgentIncomeList(AgentIncome agentIncome, boolean agentUserData){
        String whereSql = getWhereSql(agentIncome);
        List<AgentIncome> agentIncomeList = this.find(whereSql, agentIncome.getCount(), null);
        return setExtendData(agentIncomeList, agentUserData);
    }

    /**
     * 保存或修改推广员的总收益记录
     * @param agentIncome AgentIncome
     */
    public void saveOrUpdateAgentIncome(AgentIncome agentIncome){
        if(DataUtil.idIsNotNull(agentIncome.getId())){
            this.updateById(agentIncome, null);
        }else {
            save(agentIncome);
        }
    }

    /**
     * 删除推广员总收益记录
     * @param agentUserId 推广员ID
     */
    public void deleteAgentIncome(BigDecimal agentUserId){
        this.deleteWhereSql("agentUserId=" + agentUserId);
    }


    /**
     * 修改推广员的总收益数据
     * @param agentIncomeInfoList
     */
    public void updateAgentIncomeData(List<AgentIncomeInfo> agentIncomeInfoList){
        if(ObjectUtils.isNotEmpty(agentIncomeInfoList)){
            String agentUserIds = agentIncomeInfoList.stream().map(e->e.getAgentUserId().toString()).collect(Collectors.joining(","));
            List<AgentIncome> agentIncomeList = this.find("agentUserId in ("+agentUserIds+")",null,null);
            Map<BigDecimal,List<AgentIncomeInfo>> mapList  =agentIncomeInfoList.stream().collect(Collectors.groupingBy(e->e.getAgentUserId()));
            agentIncomeList.forEach(e->{
                List<AgentIncomeInfo> _incomeInfoList = mapList.get(e.getAgentUserId());
                if(ObjectUtils.isNotEmpty(_incomeInfoList)){
                    e.setOrderNum(e.getOrderNum() + _incomeInfoList.size());//累加订单数量
                    double orderSumPrice = _incomeInfoList.stream().mapToDouble(AgentIncomeInfo::getOrderPrice).sum();
                    double shopSumPrice = _incomeInfoList.stream().mapToDouble(AgentIncomeInfo::getShopPrice).sum();
                    e.setOrderSumPrice(e.getOrderSumPrice() + orderSumPrice);
                    e.setShopSumPrice(e.getShopSumPrice() + shopSumPrice);
                    double spreadIncomePrice = 0D;
                    double bonusPrice = 0D;
                    for(AgentIncomeInfo incomeInfo : _incomeInfoList){
                        if(incomeInfo.getIncomeType()==1){
                            spreadIncomePrice +=incomeInfo.getIncomePrice();
                        }
                        if(incomeInfo.getIncomeType()==2){
                            bonusPrice +=incomeInfo.getBonusPrice();
                        }
                    }
                    e.setSpreadIncomePrice(e.getSpreadIncomePrice() + spreadIncomePrice);
                    e.setBountyIncomePrice(e.getBountyIncomePrice() + bonusPrice);
                    e.setIncomeSumPrice(e.getSpreadIncomePrice() + e.getBountyIncomePrice());
                }
            });
            this.updateBatch(agentIncomeList);
        }
    }


    //==================================================
    //获取查询语句
    private String getWhereSql(AgentIncome agentIncome){
        String whereSql = "1=1";
        if(ObjectUtils.isNotEmpty(agentIncome)){
            if(DataUtil.idIsNotNull(agentIncome.getId())){
                whereSql += " and id="+ agentIncome.getId();
            }
            if(StringUtils.isNotEmpty(agentIncome.getIds())){
                whereSql += " and id in ("+ agentIncome.getIds() +")";
            }
            if(DataUtil.idIsNotNull(agentIncome.getAgentUserId())){
                whereSql += " and agentUserId=" + agentIncome.getAgentUserId();
            }
            if(StringUtils.isNotEmpty(agentIncome.getAgentUserIds())){
                whereSql += " and agentUserId in ("+ agentIncome.getAgentUserIds() +")";
            }
            if(StringUtils.isNotEmpty(agentIncome.getAgentUserName())){
                AgentUser agentUser = new AgentUser();
                agentUser.setAgentUserName(agentIncome.getAgentUserName());
                List<AgentUser> agentUsers = agentUserBiz.queryAgentUserList(agentUser, false, false, false, false);
                if(ObjectUtils.isNotEmpty(agentUsers)){
                    String agentUserIds = agentUsers.stream().map(e -> e.getId().toString()).collect(Collectors.joining(","));
                    whereSql += " and agentUserId in ("+ agentUserIds +")";
                }else {
                    whereSql += " and agentUserId=0";
                }
            }
        }
        return whereSql;
    }

    //设置扩展数据
    private List<AgentIncome> setExtendData(List<AgentIncome> agentIncomeList, boolean agentUserData){
        if(agentUserData){
            agentIncomeList = setAgentUserData(agentIncomeList, agentUserData);
        }
        return agentIncomeList;
    }

    private List<AgentIncome> setAgentUserData(List<AgentIncome> agentIncomeList, boolean agentUserData){
        if(ObjectUtils.isNotEmpty(agentIncomeList) && agentUserData){
            String agentUserIds = agentIncomeList.stream().map(e -> e.getAgentUserId().toString()).distinct().collect(Collectors.joining(","));
            AgentUser agentUser = new AgentUser();
            agentUser.setIds(agentUserIds);
            List<AgentUser> agentUsers = agentUserBiz.queryAgentUserList(agentUser, true, false, false, false);
            if(ObjectUtils.isNotEmpty(agentUsers)){
                for (AgentIncome agentIncome : agentIncomeList) {
                    for (AgentUser user : agentUsers) {
                        if(user.getId().equals(agentIncome.getAgentUserId())){
                            agentIncome.setAgentUser(user);
                            break;
                        }
                    }
                }
            }
        }
        return agentIncomeList;
    }
}
